//
//  OJCreateIssueViewController.m
//  openJira
//
//  Created by Vincent Demay on 02/05/10.
//  Copyright 2010 Goojet. All rights reserved.
//

#import "OJCreateIssueViewController.h"
#import "OJConnector.h"

@implementation OJCreateIssueViewController


- (id)initWithStyle:(UITableViewStyle)style {
    if (self = [super initWithStyle:style]) {
		
		UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"minilogo.png"]];
		self.navigationItem.titleView = imageView;
		[imageView release];
		
		UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
		temporaryBarButtonItem.title = @"Create";
		self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
		self.navigationController.navigationBar.contentMode = UIViewContentModeScaleAspectFit;
		[temporaryBarButtonItem release];
		
		//self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"create" style:UIBarButtonItemStyleBordered target:self action:@selector(onCreateTouch:)];
		
		self.tabBarItem.title = @"Create";
		self.tabBarItem.image = [UIImage imageNamed:@"create.png"];
		
		self.title = @"Create";
		
		self.hidesBottomBarWhenPushed = NO;
		
		[self.tableView setScrollEnabled:YES];
		self.tableView.allowsSelection = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

	project = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 254)];
	project.showsSelectionIndicator = YES;
	project.delegate = self;
	project.dataSource = self;
	project.tag = 1;
	[self.view addSubview:project];
	
	
	type = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 254)];
	type.showsSelectionIndicator = YES;
	type.delegate = self;
	type.dataSource = self;
	type.tag = 2;
	[self.view addSubview:type];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField resignFirstResponder];
	return NO;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
	[self hideTypePicker];
	[self hideProjectPicker];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
	[textField resignFirstResponder];
}



#pragma mark Table view methods


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	if (indexPath.row < 5) {
		return 63.0;
	}
	return 40;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 6;
}



// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		
		if (indexPath.row == 0) {
			UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(3, 3, 150, 15)];
			label.text = @"Summary:";
			label.textColor = GREY_COLOR;
			label.font = [UIFont boldSystemFontOfSize:12];
			[cell.contentView addSubview:label];
			[label release];
			
			summary = [[UITextField alloc] initWithFrame:CGRectMake(3, label.bottom + 3, cell.contentView.width - 29, 30)];
			summary.delegate = self;
			summary.borderStyle = UITextBorderStyleRoundedRect;
			summary.keyboardAppearance = UIKeyboardAppearanceAlert;
			[cell.contentView addSubview:summary];
		} else if (indexPath.row == 1) {
			UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(3, 3, 150, 15)];
			label.text = @"Description:";
			label.textColor = GREY_COLOR;
			label.font = [UIFont boldSystemFontOfSize:12];
			[cell.contentView addSubview:label];
			[label release];
			
			description = [[UITextField alloc] initWithFrame:CGRectMake(3, label.bottom + 3, cell.contentView.width - 29, 30)];
			description.delegate = self;
			description.keyboardAppearance = UIKeyboardAppearanceAlert;
			description.borderStyle = UITextBorderStyleRoundedRect;
			[cell.contentView addSubview:description];
		} else if (indexPath.row == 2) {
			UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(3, 3, 150, 15)];
			label.text = @"Project:";
			label.textColor = GREY_COLOR;
			label.font = [UIFont boldSystemFontOfSize:12];
			[cell.contentView addSubview:label];
			[label release];
			
			projectButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
			projectButton.frame = CGRectMake(3, label.bottom + 3, cell.contentView.width - 29, 30);
			[projectButton addTarget:self action:@selector(showProjectPicker) forControlEvents:UIControlEventTouchUpInside];
			[projectButton setTitle:@"Choose a project..." forState:UIControlStateNormal];
			[cell.contentView addSubview:projectButton];
		} else if (indexPath.row == 3) {
			UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(3, 3, 150, 15)];
			label.text = @"Type:";
			label.textColor = GREY_COLOR;
			label.font = [UIFont boldSystemFontOfSize:12];
			[cell.contentView addSubview:label];
			[label release];
			
			typeButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
			typeButton.frame = CGRectMake(3, label.bottom + 3, cell.contentView.width - 29, 30);
			[typeButton addTarget:self action:@selector(showTypePicker) forControlEvents:UIControlEventTouchUpInside];
			[typeButton setTitle:@"Choose a type..." forState:UIControlStateNormal];
			[cell.contentView addSubview:typeButton];
		} else if (indexPath.row == 4) {
			UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(3, 3, 150, 15)];
			label.text = @"Assignee:";
			label.textColor = GREY_COLOR;
			label.font = [UIFont boldSystemFontOfSize:12];
			[cell.contentView addSubview:label];
			[label release];
			
			UILabel *me = [[UILabel alloc] init];
			me.textColor = BG_COLOR;
			me.font = [UIFont boldSystemFontOfSize:16];
			me.textAlignment = UITextAlignmentCenter;
			me.text = @"me";
			me.frame = CGRectMake(3, label.bottom + 3, cell.contentView.width - 29, 30);
			[cell.contentView addSubview:me];
		} else {
			UIButton *send = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
			send.frame = CGRectMake(3, 3, cell.contentView.width - 29, 30);
			[send addTarget:self action:@selector(sendNewIssue) forControlEvents:UIControlEventTouchUpInside];
			[send setTitle:@"Create..." forState:UIControlStateNormal];
			[cell.contentView addSubview:send];
		}
	}
    
    // Set up the cell...
	
    return cell;
}

- (void) sendNewIssue {
	TTActivityLabel *activity = [[TTActivityLabel alloc] initWithStyle:TTActivityLabelStyleBlackBezel];
	activity.text = @"Sending...";
	[activity sizeToFit];
	activity.frame = CGRectMake(0, 100, self.view.width, activity.height);
	[self.view addSubview:activity];
	[activity setIsAnimating:YES];
	[self.view addSubview:activity];
	[activity release];
	
	int selectedIndex = [project selectedRowInComponent:0];
	OJProject* projectC = ((OJProject*)[[OJConnector getDefault].projectList.projects objectAtIndex:selectedIndex]);
	
	selectedIndex = [type selectedRowInComponent:0];
	OJType * typeC = ((OJType*)[[[OJConnector getDefault].typeList.types allValues] objectAtIndex:selectedIndex]);
		
	OJIssue * MockIssue = [[OJIssue alloc] init];
	MockIssue.summary = summary.text;
	MockIssue.description = description.text;
	MockIssue.project = projectC.key;
	MockIssue.type = [[OJConnector getDefault].typeList.types objectForKey:[NSString stringWithFormat:@"%d", typeC.lid]];
	MockIssue.delegate = self;
	//FIXME : unhardcode this
	MockIssue.assigne = @"doume";
	
	[MockIssue createIssue];
}

- (void)dealloc {
    [super dealloc];
}

/////////////////////////// ANIMATION //////////////////////////////
-(void) showProjectPicker{
	[UIView beginAnimations:@"picker" context:nil];
    [UIView setAnimationDuration:0.5];
	[summary resignFirstResponder];
	[description resignFirstResponder];
	[self hideTypePicker];
	
    project.transform = CGAffineTransformMakeTranslation(0,-254);
    [UIView commitAnimations];	
}
-(void) hideProjectPicker{
	[UIView beginAnimations:@"picker" context:nil];
    [UIView setAnimationDuration:0.5];
	
    project.transform = CGAffineTransformMakeTranslation(0,254);
    [UIView commitAnimations];	
}
-(void) showTypePicker{
	[UIView beginAnimations:@"picker" context:nil];
    [UIView setAnimationDuration:0.5];
	[summary resignFirstResponder];
	[description resignFirstResponder];
	[self hideProjectPicker];
	
    type.transform = CGAffineTransformMakeTranslation(0,-254);
    [UIView commitAnimations];	
}
-(void) hideTypePicker{
	[UIView beginAnimations:@"picker" context:nil];
    [UIView setAnimationDuration:0.5];
	
    type.transform = CGAffineTransformMakeTranslation(0,254);
    [UIView commitAnimations];	
}


//////////////////////////// PIcker View /////////////////////////////
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
	return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
	if (pickerView.tag == 1) {
		//project
		return [[OJConnector getDefault].projectList.projects count];
	} else {
		//type
		return [[OJConnector getDefault].typeList.types count];
	}
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
	if (pickerView.tag == 1) {
		//project
		return ((OJProject*)[[OJConnector getDefault].projectList.projects objectAtIndex:row]).name;
	} else {
		//type
		return ((OJType*)[[[OJConnector getDefault].typeList.types allValues] objectAtIndex:row]).name;
	}
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
	if (pickerView.tag == 1) {
		//project
		OJProject* projectC = ((OJProject*)[[OJConnector getDefault].projectList.projects objectAtIndex:row]);
		[projectButton setTitle:projectC.name forState:UIControlStateNormal];
		[self hideProjectPicker];
	} else {
		//type
		OJType * typeC = ((OJType*)[[[OJConnector getDefault].typeList.types allValues] objectAtIndex:row]);
		[typeButton setTitle:typeC.name forState:UIControlStateNormal];
		[self hideTypePicker];
	}
	
}

//////////////////////////// RESULT OF CREATION //////////////////////////

- (void) object:(OJIssue*) filter isCreated:(BOOL) onError {
	if (onError) {
		//TODO display an Alert
	}
	[self.navigationController popViewControllerAnimated:YES];
}

@end

